package hiar.hiscene.com.mysocket;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView mTextView = null;
    private EditText mEditText = null;
    private Button mServerButton = null;
    private Button mClientButton = null;
    private Button mSendButton = null;
    private MySocketServer mServer = null;
    private MySocketClient mClient = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mServer = new MySocketServer();
        mClient = new MySocketClient();
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.socket_textview);
        mEditText = (EditText) findViewById(R.id.socket_editText);
        mServerButton = (Button) findViewById(R.id.socket_server_btn);
        mClientButton = (Button) findViewById(R.id.socket_client_btn);
        mSendButton = (Button) findViewById(R.id.socket_send_btn);
        mServerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mServer.startServer(8888, new MySocketListener() {
                    @Override
                    public void OnConnect(boolean success) {
                    }

                    @Override
                    public String OnMessage(String data) {
                        Message m = new Message();
                        m.obj = data;
                        mHandler.sendMessage(m);
                        return null;
                    }
                });
            }
        });
        mClientButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClient.startClient("127.0.0.1", 8888, new MySocketListener() {
                    @Override
                    public void OnConnect(boolean success) {
                    }

                    @Override
                    public String OnMessage(String data) {
                        return null;
                    }
                });
            }
        });
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClient.send(mEditText.getText().toString());
            }
        });
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mTextView.append("\n");
            mTextView.append(msg.obj.toString());
        }
    };
}
